# -*- coding: utf-8 -*- 
"""
Created by hcx on 17-7-24 上午9:43.
@author: 胡超翔
"""
from __future__ import absolute_import
from __future__ import unicode_literals

import logging

from django.contrib.auth.mixins import LoginRequiredMixin
from django.forms.models import model_to_dict
from django.http import HttpResponse
from django.http import JsonResponse
from django.views.generic import DetailView
from django.views.generic import View

from autodeploy.apps.common.search import SearchView
from autodeploy.apps.operation.models import OperationLog, OperationDetail
from autodeploy.apps.server.models import Server

logger = logging.getLogger(__name__)


def create_log(operation_log, result, detail_status,status=None):
    if status == 'defeat':
        operation_log.status = status
        operation_log.save()
    try:
        OperationDetail.objects.create(operation_log=operation_log,
                                       result=result,status=detail_status)
    except Exception as e:
        logger.error('运行错误:%s' % e)
        return False
    return True


class ListOperationView(LoginRequiredMixin, SearchView):
    """获取日志列表"""
    template_name = 'operation/list.html'
    model = OperationLog
    context_object_name = 'operation_list'
    name_list = ['version', 'server_ip', 'books_name']
    
    def get_context_data(self, **kwargs):
        context = super(ListOperationView, self).get_context_data(**kwargs)
        server = self.get_server()
        status_tuple = OperationLog.RESULT_STATUS
        status = self.request.GET.get('status', '')
        self.status_show = '全部'
        queryset = self.search()
        if status:
            for t in status_tuple:
                if t[0] == status:
                    self.status_show = t[1]
        if server:
            context[self.context_object_name] = queryset.filter(server=server)
            context['server'] = server
        else:
            context['server'] = None
            context[self.context_object_name] = queryset
        context['status_show'] = self.status_show
        context['status_tuple'] = status_tuple
        context['status'] = status
        return context
    
    def get_server(self):
        sid = self.request.GET.get('sid')
        try:
            server = Server.objects.get(pk=sid)
        except Exception as e:
            logger.error('不存在该服务器,错误:%s' % e)
            server = None
        return server


class DetailOperationView(LoginRequiredMixin, DetailView):
    """日志详情"""
    template_name = 'operation/detail.html'
    model = OperationLog
    context_object_name = 'detail_list'
    
    def get_context_data(self, **kwargs):
        context = super(DetailOperationView, self).get_context_data(**kwargs)
        context[self.context_object_name] = self.get_object().operationdetail_set.filter()
        context['operation_log'] = self.get_object()
        return context


class DeleteOperationView(LoginRequiredMixin, View):
    """删除日志"""
    
    def get(self, request, *args, **kwargs):
        result = 0  # 0是删除失败
        try:
            oid = self.kwargs.get('oid', None)
            operation = OperationLog.objects.get(pk=oid)
            result = operation.update_delete()
            logger.info(u'%s删除日志成功%s' % (request.user, oid))
        except Exception as e:
            logger.error(u'删除日志出错,错误信息:%s' % e)
        
        return HttpResponse(result)


# @require_websocket
def get_operation_list(request):
    result = {'code': 0, 'operation_list': []}
    operation_list = OperationLog.objects.filter()[:10]
    for operation in operation_list:
        operation_dir = model_to_dict(operation)
        if operation_dir['end_time']:
            operation_dir['end_time'] = operation_dir['end_time'].strftime('%Y-%m-%d %H:%M:%S')
        else:
            operation_dir['end_time'] = ''
        operation_dir['create_time'] = operation.create_time.strftime('%Y-%m-%d %H:%M:%S')
        if operation.books_name:
            operation_dir['play_book_name'] = operation.books_name
        else:
            operation_dir['play_book_name'] = '更新'
            operation_dir['play_books'] = '更新'
        result['operation_list'].append(operation_dir)
    result['operation_list'].reverse()
    result['code'] = 1
    # result = json.dumps(result)
    # if request.is_websocket():
    #     request.websocket.send(result)
        # import uwsgi
        # uwsgi.websocket_handshake()
        # # import uwsgi
        # uwsgi.websocket_send(result)
    # else:
    return JsonResponse(result)
# def application(env, start_response):
#     # complete the handshake
#     uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
#     while True:
#         msg = uwsgi.websocket_recv()
#         uwsgi.websocket_send(msg)